﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Text;
using Cms.EntLib;
using System.IO;

namespace Cms.Web.UIBuilder
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class DesignForm : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string type = EntLib.Request.GetString("action");
            switch (type)
            {
                case "saveform":
                    SaveFormXmlData();
                    break;
                case "getformjson":
                    GetFormJson();
                    break;
                default:
                    break;
            }
        }
        public void GetFormJson()
        {
            string formid = EntLib.Request.GetString("formid");
            string param = EntLib.Request.GetString("param");
            string text = "";
            if (param == "list")
            {
                BLL.Sys_Selffom_List_Layout blllistlayout = new Cms.BLL.Sys_Selffom_List_Layout();
                try
                {
                    Model.Sys_Selfform_List_Layout modellayout = blllistlayout.GetById(formid, false);
                    if (modellayout != null)
                    {
                        text = modellayout.Jsondata;
                    }
                }
                catch { }
            }
            if (param == "model")
            {
                BLL.Sys_Selfform_Layout blllistlayout = new Cms.BLL.Sys_Selfform_Layout();
                try
                {
                    Model.Sys_Selfform_Layout modellayout = blllistlayout.GetById(formid, false);
                    if (modellayout != null)
                    {
                        text = modellayout.Jsondata;
                    }
                }
                catch { }

            }
            if (String.IsNullOrEmpty(text))
            {
                var template = HttpContext.Current.Server.MapPath("~/Scripts/Linb/VisualJS/template/index.js");
                HttpContext.Current.Response.WriteFile(template);
            }
            else
            {
                ResponseText(text);
            }
        }

        private void SaveFormXmlData()
        {
            StringBuilder Result = new StringBuilder();
            string xmldata = EntLib.Request.GetString("xmldata");
            string jsondata = EntLib.Request.GetString("jsondata");
            string formid = EntLib.Request.GetString("formid");
            string issys = Request.GetString("issys");
            string param = Request.GetString("param");
            if (issys == "true")
                Result.Append(SaveSysForm(formid, xmldata, jsondata));
            else
                Result.Append(SaveBussinessForm(formid, param, xmldata, jsondata));
            ResponseText(Result.ToString());
        }

        public string SaveSysForm(string formid, string xmldata, string jsondata)
        {
            xmldata = System.Web.HttpUtility.UrlDecode(xmldata);
            jsondata = System.Web.HttpUtility.UrlDecode(jsondata);
            jsondata = "Class('App', 'linb.Com', {Instance: {base: ['linb.UI'],required: [],properties: {},events: {},iniResource:function(com, threadid) {},iniComponents: function(com, threadid) {" + jsondata;
           // jsondata += "\r\n},iniExComs: function(com, hreadid) {}}});";
            string result = "";
            try
            {
                string folder = Request.GetString("folder");
                string path = HttpContext.Current.Server.MapPath("~/CmsSystem/SysModules");
                if (!path.EndsWith("/"))
                    path += "/";
                if (!String.IsNullOrEmpty(folder))
                    path += folder;
                path = String.Format("{0}/{1}", path, formid);
                string jspath = path + ".js";
                string xmlpath = path + ".xml";
                if (File.Exists(jspath))
                    File.Delete(jspath);
                if (File.Exists(xmlpath))
                    File.Delete(xmlpath);
                File.AppendAllText(path + ".js", jsondata);
                File.AppendAllText(path + ".xml", xmldata);

            }
            catch (Exception e)
            {
                result = e.Message;
            }
            return result;
        }
        public string SaveBussinessForm(string formid, string param, string xmldata, string jsondata)
        {
            string result = "";
            xmldata = System.Web.HttpUtility.UrlDecode(xmldata);
            jsondata = System.Web.HttpUtility.UrlDecode(jsondata);
            jsondata = "Class('App', 'linb.Com', {Instance: {base: ['linb.UI'],required: [],properties: {},events: {},iniResource:function(com, threadid) {},iniComponents: function(com, threadid) {" + jsondata;
            //jsondata += "\r\n},iniExComs: function(com, hreadid) {}}});";
            if (param == "list")
            {
                BLL.Sys_Selffom_List_Layout bll = new Cms.BLL.Sys_Selffom_List_Layout();
                //在此 formid 其实是 列表的主键.
                Model.Sys_Selfform_List_Layout model = bll.GetById(formid, false);
                if (model == null)
                {
                    model = new Cms.Model.Sys_Selfform_List_Layout();
                    model.Id = System.Guid.NewGuid().ToString();
                }
                model.Jsondata = jsondata;
                model.Xmldata = xmldata;
                bll.SaveOrUpdate(model);
                bll.CommitChanges();
            }
            if (param == "model")
            {
                BLL.Sys_Selfform_Layout bll = new Cms.BLL.Sys_Selfform_Layout();
                Model.Sys_Selfform_Layout model = null;
                /*try
                {
                    model = bll.GetById(formid, false);
                }
                catch { }
                */
                //Model.Sys_Selfform_Layout model = new Cms.Model.Sys_Selfform_Layout();
                if (model == null)
                {
                    model = new Cms.Model.Sys_Selfform_Layout();
                }

                model.Id = formid;
                model.Jsondata = jsondata;
                model.Xmldata = xmldata;
                //model.Listid = "";
                model.Updatedate = DateTime.Now;
                //model.Layoutid 
                //model.Title = "";
                bll.SaveOrUpdate(model);
                bll.CommitChanges();
            }
            return result;
        }
        //private string BuilderAjax

        void ResponseText(string text)
        {
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            HttpContext.Current.Response.Expires = -1;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(text);
            HttpContext.Current.Response.End();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
